package com.corecmd.tcloud.tcimserver.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : tianshaojiao
 * @version : 1.0
 * @apiNote : 封装HttpClient方法
 * @date : 2019/12/16
 * @copyright :
 */
@Slf4j
public class HttpClientUtils {
    public static String httpFormPost(String url, Map<String, String> params, Map<String, String> headers, Charset charset) throws Exception {
        log.info("发起HTTP POST请求：" + url);
        String requestResult = null;
        CloseableHttpClient closeableHttpClient = HttpClientUtils.createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        if (null == charset){
            charset = Charsets.toCharset("UTF-8");
        }
        if (null != headers && !headers.isEmpty()){
            for (Map.Entry<String, String> entry:headers.entrySet()) {
                httpPost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        if (null != params && !params.isEmpty()){
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry:params.entrySet()) {
                NameValuePair pai1 = new BasicNameValuePair(entry.getKey(),entry.getValue());
                list.add(pai1);
            }
            HttpEntity httpEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
            httpPost.setEntity(httpEntity);
        }
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
        if (null != closeableHttpResponse){
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset));
            String tempStr = "";
            StringBuffer sb = new StringBuffer();
            while ( (tempStr = bufferedReader.readLine()) != null){
                sb.append(tempStr);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        }
        if (null != closeableHttpResponse){
            closeableHttpResponse.close();
        }
        closeableHttpClient.close();
        log.info("请求结果："+requestResult);
        return requestResult;
    }
    public static String httpPost(String url, Map<String, String> params, Map<String, String> headers, Charset charset) throws Exception {
        log.info("发起HTTP POST请求：" + url);
        String requestResult = null;
        CloseableHttpClient closeableHttpClient = HttpClientUtils.createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        if (null == charset){
            charset = Charsets.toCharset("UTF-8");
        }
        if (null != headers && !headers.isEmpty()){
            for (Map.Entry<String, String> entry:headers.entrySet()) {
                httpPost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        if (null != params && !params.isEmpty()){
            JSONObject jsonObject = (JSONObject) JSON.toJSON(params);
            String requestParams = jsonObject.toJSONString();
            HttpEntity httpEntity = new StringEntity(requestParams, charset);
            httpPost.setEntity(httpEntity);
        }
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
        if (null != closeableHttpResponse){
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset));
            String tempStr = "";
            StringBuffer sb = new StringBuffer();
            while ( (tempStr = bufferedReader.readLine()) != null){
                sb.append(tempStr);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        }
        if (null != closeableHttpResponse){
            closeableHttpResponse.close();
        }
        closeableHttpClient.close();
        log.info("请求结果："+requestResult);
        return requestResult;
    }
    public static String httpGet(String url, Map<String, String> headers, Charset charset) throws Exception {
        log.info("发起HTTP Get请求：" + url);
        String requestResult = null;
        CloseableHttpClient closeableHttpClient = HttpClientUtils.createSSLClientDefault();
        HttpGet httpGet = new HttpGet(url);
        if (null == charset){
            charset = Charsets.toCharset("UTF-8");
        }
        if (null != headers && !headers.isEmpty()){
            for (Map.Entry<String, String> entry:headers.entrySet()) {
                httpGet.addHeader(entry.getKey(),entry.getValue());
            }
        }
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
        if (null != closeableHttpResponse){
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset));
            String tempStr = "";
            StringBuffer sb = new StringBuffer();
            while ( (tempStr = bufferedReader.readLine()) != null){
                sb.append(tempStr);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        }
        if (null != closeableHttpResponse){
            closeableHttpResponse.close();
        }
        closeableHttpClient.close();
        return requestResult;
    }
    public static CloseableHttpClient createSSLClientDefault(){
        CloseableHttpClient closeableHttpClient = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
            closeableHttpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (Exception e) {
            log.info("解决Https异常",e);
        }
        return closeableHttpClient;
    }
    public static void craw5kmm(){
        String url = "http://www.5kmm.com/";
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");
            headers.put("Host","bdimg.share.baidu.com");
            headers.put("Referer","http://www.5kmm.com/");
            Map<String, String> params = new HashMap<String, String>();
            String reqResult = HttpClientUtils.httpGet(url,headers,Charsets.toCharset("gb2312"));
            if (null != reqResult){
                Document doc = Jsoup.parse(reqResult);
                log.info(doc.html());
            }
        } catch (Exception e) {
            log.info("http请求异常",e);
        }
    }
    public static String uploadFile(String url, Map<String, String> params, Map<String, String> headers, List<File> files, Charset charset) throws Exception {
        log.info("发起HTTP 文件上传请求：" + url);
        CloseableHttpClient closeableHttpClient = HttpClientUtils.createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        if (null != headers && !headers.isEmpty()){
            for (Map.Entry<String, String> entry:headers.entrySet()) {
                httpPost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (null != params && !params.isEmpty()){
            for (Map.Entry<String, String> entry:params.entrySet()) {
                // 相当于<input type="text" name="userName" value=userName>
                multipartEntityBuilder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create(
                        "text/plain", Consts.UTF_8)));
            }
        }
        if (null == charset){
            charset = Charsets.toCharset("UTF-8");
        }
        for (int i = 0,len = files.size(); i < len; i++) {
            // 把文件转换成流对象FileBody
            FileBody toUploadFile = new FileBody(files.get(i));
            multipartEntityBuilder.addPart("file"+i,toUploadFile);
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
        String requestResult="";
        if (null != closeableHttpResponse){
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset));
            String tempStr = "";
            StringBuffer sb = new StringBuffer();
            while ( (tempStr = bufferedReader.readLine()) != null){
                sb.append(tempStr);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        }
        if (null != closeableHttpResponse){
            closeableHttpResponse.close();
        }
        closeableHttpClient.close();
        return requestResult;
    }
    public static void main(String[] args) {

    }
}
